from rest_framework import serializers
from .models import Topic,UserTopic,Post, Permission, Image
from user.models import UserModel,FollowModel
class TopicSerializer(serializers.ModelSerializer):
    class Meta:
        model = Topic
        fields = '__all__'
class TopicReadSerializer(serializers.ModelSerializer):
    class Meta:
        model = Topic
        fields = ['id','title']
class UserSer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ['nickname','headimg','id']

class UserTopicSerializer(serializers.ModelSerializer):
    #user=UserSer()
    userlist=serializers.SerializerMethodField()
    isfollow=serializers.SerializerMethodField()
    def get_userlist(self,obj):
        img=str(obj.user.headimg)
        if img:
            imgstr="http://127.0.0.1:8000"+img
        else:
            imgstr="http://127.0.0.1:8000/uploads/headimg/default.jpeg"
        #判断当前用户是否关注某个用户
        return {"nickname":obj.user.nickname,"headimg":imgstr,"id":obj.user.id}
    def get_isfollow(self,obj):
        # 获取当前请求的用户（假设用户已通过认证）
        user = self.context['request'].query_params.get("user")
        info=FollowModel.objects.filter(follower=user,following=obj.user.id)
        if info:
            return True
        else:
            return False

    class Meta:
        model = UserTopic
        fields = '__all__'

class UserTopicListSerializer(serializers.ModelSerializer):
    topiclist=serializers.SerializerMethodField()
    def get_topiclist(self,obj):
        return {"title":obj.topic.title,"id":obj.topic.id,"views":obj.topic.views}
    class Meta:
        model = UserTopic
        fields = '__all__'


class TopicListSerializer(serializers.ModelSerializer):
    follow = serializers.SerializerMethodField()
    class Meta:
        model = Topic
        fields = "__all__"
    def get_follow(self, obj):
        # 获取当前请求的用户（假设用户已通过认证）
        user = self.context['request'].query_params.get("user")
        # 检查用户是否已关注该话题
        is_following = UserTopic.objects.filter(user=user, topic=obj).exists()
        return is_following

class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = '__all__'

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = '__all__'

class PostSerializer(serializers.ModelSerializer):
    topics = TopicReadSerializer(many=True, read_only=True)
    # permission = PermissionSerializer(read_only=True)
    images = ImageSerializer(many=True, read_only=True)

    # def create(self, validated_data):
    #     print(validated_data)
    #     # 提取多对多字段数据
    #     #topics_data = validated_data.pop('topics')
    #     # 创建 Post 实例
    #     post = Post.objects.create(**validated_data)
    #     # 关联 Topic
    #     post.topics.set(topics_data)
    #     return post
    class Meta:
        model = Post
        fields = '__all__'